import os
import shutil
import sys
import time

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))


def rmtree(dir_path: str):
    times = 1
    while 1:
        if not os.path.isdir(dir_path):
            print(f'{dir_path}目录已删除')
            return True
        if times >= 10:
            raise Exception(f'{dir_path}目录未删除')
        shutil.rmtree(dir_path)
        times += 1


def mkdirs(dir_path: str):
    times = 1
    while 1:
        if os.path.isdir(dir_path):
            print(f'{dir_path}目录创建成功')
            return True
        if times >= 10:
            raise Exception(f'{dir_path}目录创建失败')
        os.makedirs(dir_path, exist_ok=True)
        times += 1


def build_mac():
    cmd = f"pyinstaller main.py --noconsole --noconfirm --hidden-import PySide6.QtXml"
    cmd = f"pyinstaller main.py --noconfirm --hidden-import PySide6.QtXml --distpath {PROJECT_PATH}/output --workpath {PROJECT_PATH}/build"

    rmtree(f'{PROJECT_PATH}/output')

    print(cmd)
    os.system(cmd)

    if not os.path.isdir(f"{PROJECT_PATH}/output"):
        print(f"{PROJECT_PATH}/output is not exists")
        return False
    shutil.copytree(f"{PROJECT_PATH}/resource", f"{PROJECT_PATH}/output/main/_internal/resource")
    shutil.copytree(f"{PROJECT_PATH}/sql-editor", f"{PROJECT_PATH}/output/main/_internal/sql-editor")
    shutil.copy(f"{PROJECT_PATH}/connection.json", f"{PROJECT_PATH}/output/main/_internal/")
    print(f'打包成功，目录为：{PROJECT_PATH}/output/')


def build_win():
    rmtree(f'{PROJECT_PATH}/main.build')
    rmtree(f'{PROJECT_PATH}/output')

    # 开始打包
    cmd = f'nuitka --mingw64 --standalone --show-memory ' \
          f'--windows-disable-console ' \
          f'--show-progress --plugin-enable=pyside6 ' \
          f'--nofollow-import-to=tkinter,mpl_toolkits ' \
          f'--plugin-enable=tk-inter ' \
          f'--output-dir=output ' \
          f'--output-filename=sequel-mysql ' \
          f'--windows-icon-from-ico={PROJECT_PATH}/resource/asset/logo/logo.ico main.py'

    os.environ['pythonpath'] = f"{PROJECT_PATH}/venv\Lib\site-packages"
    os.system(cmd)
    time.sleep(5)

    # 将对应的资源文件拷入
    shutil.copy(f'{PROJECT_PATH}/connection.conf', f'{PROJECT_PATH}/output/main.dist/')
    shutil.copytree(f'{PROJECT_PATH}/resource', f'{PROJECT_PATH}/output/main.dist/resource')
    shutil.copytree(f'{PROJECT_PATH}/sql-editor', f'{PROJECT_PATH}/output/main.dist/sql-editor')

    print(f'打包成功，目录为：{PROJECT_PATH}/dist/main')


def main():
    if sys.platform == 'win32':
        print("运行在Windows系统上")
    elif sys.platform == 'linux':
        print("运行在Linux系统上")
    elif sys.platform == 'darwin':
        print("运行在macOS系统上")
        build_mac()
    else:
        print("运行在其他系统上")




if __name__ == '__main__':
    main()
